<?php
require_once("{$CfgPara->root}/model/user.m.php");
require_once("{$CfgPara->root}/class/mysql.func.php");

/**
 * 支付类，方便用户使用第三方工具支付
 */
class CPay
{
    /** 支付工具 支付宝 */
    const PayToolZhiFuBao = 1;
    /** 支付工具 微信支付 */
    const PayToolWeiXin = 2;
    /** 支付工具 使用余额 */
    const PayToolBalance = 3;

    /** 商品单价 余额充值 1元 */
    const GoodsPrice_Balance = 1;
    /** 商品单价 作品发布 2元 */
    const GoodsPrice_WorkRelease = 2;
    /** 商品单价 鞋主秀发布 2元 */
    const GoodsPrice_ShowRelease = 2;
    /** 商品单价 用户本领添加 */
    const GoodsPrice_FieldAdd = 2;
    /** 商品单价 用户本领修改名称 */
    const GoodsPrice_FieldName = 1;
    /** 商品单价 用户本领修改简介 */
    const GoodsPrice_FieldIntrod = 1;
    /** 商品单价 用户本领添加作品 */
    const GoodsPrice_FieldWorkAdd = 1;
    /** 商品单价 用户本领删除作品 */
    const GoodsPrice_FieldWorkDele = 1;

    /** 商品类型 余额充值 */
    const GoodsType_Balance = 1;
    /** 商品类型 作品发布 */
    const GoodsType_WorkRelease = 2;
    /** 商品类型 鞋主秀发布 */
    const GoodsType_ShowRelease = 3;
    /** 商品类型 用户本领添加 */
    const GoodsType_FieldAdd = 30;
    /** 商品类型 用户本领修改名称 */
    const GoodsType_FieldName = 31;
    /** 商品类型 用户本领修改简介 */
    const GoodsType_FieldIntrod = 32;
    /** 商品类型 用户本领添加作品 */
    const GoodsType_FieldWorkAdd = 33;
    /** 商品类型 用户本领删除作品 */
    const GoodsType_FieldWorkDele = 34;

    /** 消费类型 余额充值 */
    const ConsumeType_Balance = 0;
    /** 消费类型 作品发布 */
    const ConsumeType_WorkRelease = 1;
    /** 消费类型 鞋主秀发布 */
    const ConsumeType_ShowRelease = 2;
    /** 消费类型 本领编辑 (具有多个子项)*/
    const ConsumeType_FieldEdit = 3;

    /** 订单状态 提交中 */
    const OrderState_Submit = 0;
    /** 订单状态 未支付 */
    const OrderState_NoPay = 1;
    /** 订单状态 已支付完成 */
    const OrderState_PayOK = 2;
    /** 订单状态 已过期 */
    const OrderState_Expired = 10;
    /** 订单状态 用户已删除 */
    const OrderState_UserDele = 99;

    /**
     * 支付宝支付 配置
     */
    public $alipay_config = null;
    public $submit_html_text = '';

    /** 微信支付 统一下单接口链接 */
    public $WeiXinPay_Url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
    /** 微信支付 公众号ID */
    public $WeiXinPay_AppID = "gh_6ee44de3a499";
    /** 微信支付 商户账户ID */
    public $WeiXinPay_MchID = "1489388122";
    /** 微信支付 API密钥 */
    public $WeiXinPay_APIKey = "27aacc360aff930149f1523f53967750";
    /** 微信支付 支付成功后 微信后台将异步调用此页面 完整路径为{$CfgPara->httproot}/payok/{$order_id}.html */
    public $WeiXinPay_Notify_Url = "payok";
    /**
     * 微信支付 用户在微信页面上完成支付后（无论是否成功）微信后台将用户浏览器回调到此页面中
     * 我们用来显示订单
     */
    public $WeiXinPay_Redirect_Url = "payorder";

    /** 余额支付 支付成功后跳转到此页面 完整路径为{$CfgPara->httproot}/payok/{$order_id}.html */
    public $BalancePay_Notify_Url = "payorder";

    public function __construct($dbPara = null)
    {
        if ($dbPara != null) {
            db_connect($dbPara);
        }
    }

    /**
     * 获取用户购物车内商品数量 成功返回数量，失败返回错误信息
     */
    public function pay_car_count($for_update = FALSE)
    {
        if (!isset ($_SESSION['user_id']) || !is_numeric($_SESSION['user_id'])) {
            return '尚未登陆';
        }
        $sql_str = "SELECT `PayCarCount` FROM `users` WHERE `Id` = {$_SESSION['user_id']}";
        if ($for_update)
            $sql_str .= ' FOR UPDATE';
        $result = db_query($sql_str);
        if ($result !== FALSE) {
            if ($count = $result->fetch_object()) {
                return (int)$count->PayCarCount;
            } else {
                return '无法获取购物车商品的数量';
            }
        } else {
            return db_error();
        }
    }

    /**
     * 获取购物车列表 成功返回对象数组 失败返回错误信息
     */
    public function pay_car_list()
    {
        if (!isset ($_SESSION['user_id']) || !is_numeric($_SESSION['user_id'])) {
            return '尚未登陆';
        }
        $sql_str = "SELECT * FROM `user_pay_car` WHERE `UserId` = {$_SESSION['user_id']}";
        $result = db_query($sql_str);
        if ($result === FALSE) return db_error();
        while ($row = $result->fetch_object()) {
            $good_id = (int)$row->GoodId;
            // 给购物车商品对象添加一个价格属性
            $row->Price = $this->get_good_price($good_id);
            // 给购物车商品对象添加标题和内容属性
            if ($this->get_good_desc($good_id, $row) === 1) {
                $rows[] = $row;
            } else {
                return '获取商品的描述时错误';
            }
        }
        // 如果之前都没定义到$rows 则返回个空的数组
        if (!isset ($rows)) $rows = array();
        return $rows;
    }

    /**
     * 根据商品Id获取商品价格
     */
    public function get_good_price($good_id)
    {
        $good_id = (int)$good_id;
        switch ($good_id) {
            case CPay::GoodsType_Balance:
                return CPay::GoodsPrice_Balance;
            case CPay::GoodsType_ShowRelease:
                return CPay::GoodsPrice_ShowRelease;
            case CPay::GoodsType_WorkRelease:
                return CPay::GoodsPrice_WorkRelease;
            case CPay::GoodsType_FieldAdd:
                return CPay::GoodsPrice_FieldAdd;
            case CPay::GoodsType_FieldIntrod:
                return CPay::GoodsPrice_FieldIntrod;
            case CPay::GoodsType_FieldName:
                return CPay::GoodsPrice_FieldName;
            case CPay::GoodsType_FieldWorkAdd:
                return CPay::GoodsPrice_FieldWorkAdd;
            case CPay::GoodsType_FieldWorkDele:
                return CPay::GoodsPrice_FieldWorkDele;
            default:
                return 0;
        }
    }

    /**
     * 根据商品Id 获取商品描述（标题与内容文本） 成功返回1 失败返回0
     * @param int $good_id 商品id
     * @param int $data 购物车中商品对象数据 将在此对象中添加标题与内容属性
     */
    public function get_good_desc($good_id, &$data)
    {
        $good_id = (int)$good_id;
        switch ($good_id) {
            case CPay::GoodsType_FieldAdd:
                $data->Tittle = '添加【本领】';
                $data->ContentText = $data->Text;
                break;
            case CPay::GoodsType_FieldIntrod:
                $data->Tittle = '修改【本领简介】';
                $data->ContentText = "修改本领\"{$data->Text}\"的简介为\"{$data->Text2}\"";
                break;
            case CPay::GoodsType_FieldName:
                $data->Tittle = '修改【本领名称】';
                $data->ContentText = "修改本领名称\"{$data->Text}\"为\"{$data->Text2}\"";
                break;
            case CPay::GoodsType_FieldWorkAdd:
                $data->Tittle = '添加【作品】';
                $data->ContentText = "添加作品《{$data->Text2}》到\"{$data->Text}\"";
                break;
            case CPay::GoodsType_FieldWorkDele:
                $data->Tittle = '删除【作品】';
                $data->ContentText = "从本领\"{$data->Text}\"删除作品《{$data->Text2}》";
                break;
            default:
                return 0;
        }
        return 1;
    }

    /**
     * 删除ids中的购物车内的商品 成功返回1 失败返回错误信息
     * @param string $ids 删除的商品id的字符串 用逗号分隔
     */
    public function pay_car_dele(&$ids)
    {
        $ids = rtrim($ids, ',');
        if (empty($ids)) return 1; // 没有需要删除的
        $id_array = explode(',', rtrim($ids, ','));
        // 检查所有id是否合法
        foreach ($id_array as $id) {
            if (!is_numeric($id)) return '购物车删除时，提交的信息错误';
        }
        $count = count($id_array);
        // 开始事务
        db_begin();
        // 删除购物车中的相关内容
        $sql_str = "DELETE FROM `user_pay_car` 
					WHERE `UserId` = {$_SESSION['user_id']} AND `Id` IN ({$ids})";
        $result = db_query($sql_str);
        if ($result === FALSE) {
            return db_rollback();
        }
        // 如果删除购物车中的数量为0 表示没有相关内容 当前按删除完成处理
        if (db_affected_rows() < $count) {
            db_rollback();
            return '购物车删除时，提交的信息有误';
        }
        // 删除掉本领的相关内容
        $sql_str = "DELETE FROM `user_field` WHERE `ViewState`=0 AND `PayCarId` IN ($ids)";
        $result = db_query($sql_str);
        if ($result === FALSE) {
            db_rollback();
        }
        // 此处删除的本领为未付费的，users表中记录的数据为仅已付费的数量 无需更新

        // 删除掉本领的作品的相关内容
        $sql_str = "DELETE FROM `user_field_works` WHERE `ViewState`=0 AND `PayCarId` IN ($ids)";
        $result = db_query($sql_str);
        if ($result === FALSE) {
            db_rollback();
        }

        // 更新用户购物车中的商品数
        $sql_str = "UPDATE `users` SET `PayCarCount` = `PayCarCount` - {$count}
					WHERE `Id` = {$_SESSION['user_id']}";
        $result = db_query($sql_str);
        if ($result === FALSE) {
            db_rollback();
        }
        // 提交事务
        db_commit();
        return 1;
    }

    /**
     * 删除购物车中的一个商品 成功返回1 失败返回错误信息
     * @param int $id 购物车中的id
     * @param int $update_count 是否更新用户的购物车数量 1是 0不在此处更新
     */
    public function pay_car_dele_one($id, $update_count = 0)
    {
        if (!is_numeric($id)) return '购物车删除某个商品时，提交的信息错误';
        $sql_str = "DELETE FROM `user_pay_car` 
                    WHERE `Id` = {$id} AND `UserId` = {$_SESSION['user_id']}";
        $result = db_query($sql_str);
        if ($result === FALSE) return db_error();
        // 更新用户的购物车数量
        if ($update_count === 1) {
            $result = $this->pay_car_update_count(0, 1);
            if ($result !== 1) return $result;
        }
        return 1;
    }

    /**
     * 更新用户的购物车数量 类型0为减 类型1为加 成功返回1 失败返回错误信息
     */
    public function pay_car_update_count($type, $value)
    {
        if ($type == 0) $flag = '-'; // 减少
        elseif ($type == 1) $flag = '+';
        else return '更新购物数量的类型错误';
        $sql_str = "UPDATE `users` SET `PayCarCount` = `PayCarCount` {$flag} {$value}
					WHERE `Id` = {$_SESSION['user_id']}";
        $result = db_query($sql_str);
        if ($result === FALSE) return db_error();
        return 1;
    }

    /**
     * 删除购物车中属于某个本领的作品添加 成功返回删除了多少条 失败返回错误信息
     * @param int $field_id 本领id
     * @param int $update_count 是否更新用户的购物车数量 1是 0不在此处更新
     */
    public function pay_car_dele_works($field_id, $update_count = 0)
    {
        if (!is_numeric($field_id)) return '购物车删除属于本领的作品添加时，提交的信息错误';
        $good_id = CPay::GoodsType_FieldWorkAdd;
        $sql_str = "DELETE FROM `user_pay_car`
					WHERE `GoodId` = {$good_id} AND ContentId = {$field_id} AND 
						  `UserId` = {$_SESSION['user_id']}";
        $result = db_query($sql_str);
        if ($result === FALSE) return db_error();
        $count = db_affected_rows();
        if ($update_count === 1) {
            $result = $this->pay_car_update_count(0, $count);
            if ($result !== 1) return $result;
        }
        return $count;
    }

    /**
     * 购物车添加商品 正确返回购物车添加商品的数量 错误返回错误信息
     */
    public function pay_car_add(&$data)
    {
        // 插入购物车 返回购物车id
        // 开始事务
        db_begin();
        $good_id = (int)$data['pay_car_good'];
        switch ($good_id) {
            case CPay::GoodsType_FieldAdd:
                $count = $this->pay_car_add_fieldadd($data);
                break;
            case CPay::GoodsType_FieldName:
                $count = $this->pay_car_add_fieldname($data);
                break;
            case CPay::GoodsType_FieldIntrod:
                $count = $this->pay_car_add_fieldintrod($data);
                break;
            case CPay::GoodsType_FieldWorkAdd:
                $count = $this->pay_car_add_fieldwork($data);
                break;
            //case CPay::GoodsType_FieldWorkDele: $count = $this->pay_car_add_fieldwork($data); break ;
            default :
                return '加入购物车时，商品类型未找到';
        }
        // 购物车添加成功后 增加当前用户的购物车商品数量
        if (is_numeric($count) && $count > 0) {
            $sql_str = "UPDATE `users` SET `PayCarCount` = `PayCarCount` + {$count}
						WHERE `Id` = {$_SESSION['user_id']}";
            $result = db_query($sql_str);
            if ($result === FALSE) {
                return db_rollback();
            }
            // 提交事务
            db_commit();
        } else {
            return db_rollback();
        }
        return $count;
    }

    /**
     * 购物车添加商品 本领添加
     */
    private function pay_car_add_fieldadd(&$data)
    {
        global $CfgPara;
        if (isset ($data['field_name']) && isset ($data['field_introd'])) {
            $good_id = CPay::GoodsType_FieldAdd;
            $name = db_escape(urldecode($data['field_name']));
            if ($name == FALSE) return '本领名称的内容不合法';
            $tLen = mb_strlen($name, 'utf8');
            if ($tLen < 3 || $tLen > 30) return '本领的名称长度必须大于等于3小于30';

            // 检查当前是否已有此本领名称 包括在购物车中检查
            $sql_str = "SELECT `Id` FROM `user_field` 
						WHERE `UserId` = {$_SESSION['user_id']} AND `FieldName` = '{$name}'
						UNION ALL 
						SELECT `Id` FROM `user_pay_car` 
						WHERE `UserId` = {$_SESSION['user_id']} AND
							  `GoodId` = {$good_id} AND 
							  `Text` = '{$name}'";
            $result = db_query($sql_str);
            if ($result === FALSE) {
                return db_error();
            }
            if ($result->num_rows > 0) {
                return '您已存在当前本领';
            }

            $introd = db_escape(urldecode($data['field_introd']));
            if ($introd == FALSE) return '本领简介的内容不合法';
            $tLen = mb_strlen($introd, 'utf8');
            if ($tLen < 5 || $tLen > 128) return '本领的简介长度必须大于等于5小于128';

            // 插入购物车
            $sql_str = "INSERT INTO `user_pay_car` 
						SET `UserId` = {$_SESSION['user_id']},
						    `GoodId` = {$good_id},
							`Text` = '{$name}',
							`Text2` = '{$introd}'";
            $result = db_query($sql_str);
            if ($result === FALSE) return db_error();
            $id = db_insert_id(); // 返回插入的id

            // 插入新的本领 但是此时本领前台不可见 直到付费后
            $myUser = new user_m();
            $result = $myUser->user_field_insert($name, $introd, 0, $id);
            if (!is_numeric($result)) return db_error();
            $field_id = db_insert_id();

            // 将购物车的内容Id更新
            $sql_str = "UPDATE `user_pay_car` SET ContentId = {$field_id}
						WHERE Id = {$id}";
            $result = db_query($sql_str);
            if ($result === FALSE) return db_error();
            // if ($id != 0) return  $id;
            // else return '本领添加的购物车添加失败';
            return 1;
        } else {
            return '找不到本领的名称或简介内容';
        }
    }

    /**
     * 购物车添加商品 本领修改名称
     */
    private function pay_car_add_fieldname(&$data)
    {
        global $CfgPara;
        if (!isset ($data['field_id']) || !is_numeric($data['field_id']))
            return '提交的本领信息错误';
        if (!isset ($data['field_name'])) return '找不到本领的名称';
        $good_id = CPay::GoodsType_FieldName;
        $name = db_escape(urldecode($data['field_name']));
        if ($name == FALSE) return '本领名称的内容不合法';
        $tLen = mb_strlen($name, 'utf8');
        if ($tLen < 3 || $tLen > 30) return '本领的名称长度必须大于等于3小于30';

        // 更新本领的后台名称
        $myUser = new user_m();
        $fieldMsg;
        $result = $myUser->user_field_update($data['field_id'], $data['field_name'], '', 10, $fieldMsg);
        if (!is_numeric($result)) return $result;

        // 插入购物车
        $sql_str = "INSERT INTO `user_pay_car` 
					SET `UserId` = {$_SESSION['user_id']},
						`GoodId` = {$good_id}, 
						`ContentId` = {$data['field_id']},
						`Text` = '{$fieldMsg->FieldName}',
						`Text2` = '{$name}'";
        $result = db_query($sql_str);
        if ($result === FALSE) return db_error();
        // $id = db_insert_id(); // 返回插入的id
        return 1;
    }

    /**
     * 购物车添加商品 本领修改简介 成功返回1 失败返回错误信息
     */
    private function pay_car_add_fieldintrod(&$data)
    {
        global $CfgPara;
        if (isset ($data['field_introd'])) {
            $good_id = CPay::GoodsType_FieldIntrod;

            $introd = db_escape(urldecode($data['field_introd']));
            if ($introd == FALSE) return '本领简介的内容不合法';
            $tLen = mb_strlen($introd, 'utf8');
            if ($tLen < 5 || $tLen > 128) return '本领的简介长度必须大于等于5小于128';

            // 更新本领的后台简介
            $myUser = new user_m();
            $fieldMsg;
            $result = $myUser->user_field_update($data['field_id'], '', $data['field_introd'], 10, $fieldMsg);
            if (!is_numeric($result)) return $result;
            // 插入购物车
            $sql_str = "INSERT INTO `user_pay_car` 
						SET `UserId` = {$_SESSION['user_id']},
						    `GoodId` = {$good_id}, 
							`ContentId` = {$data['field_id']},
							`Text` = '{$fieldMsg->FieldName}',
							`Text2` = '{$introd}'";
            $result = db_query($sql_str);
            //$id = db_insert_id(); // 返回插入的id
            return 1;
        } else {
            return '找不到本领的简介内容';
        }
    }

    /**
     * 购物车添加商品 本领的作品添加 成功返回添加的数量 失败返回错误信息
     */
    private function pay_car_add_fieldwork(&$data)
    {
        if (!isset ($data['ids']) ||  // 作品的字符串用
            !isset ($data['field_id']) || !is_numeric($data['field_id'])
        ) {
            return '提交的信息错误';
        }
        $myUser = new user_m();
        // 检查本领是否存在 以及是否属于用户
        $fieldMsg;
        $result = $myUser->user_field_own_check($data['field_id'], $_SESSION['user_id'], $fieldMsg);
        if ($result !== 1) return $result;

        // 检测作品是否存在 并且检查作品是否属于用户
        $workList;
        $result = $myUser->user_field_work_check($data['ids'], $workList);
        if ($result !== 1) return $result;
        $count = 0;
        foreach ($workList as $work) {
            // 插入购物车
            $sql_str = "INSERT INTO `user_pay_car` 
						SET `UserId` = {$_SESSION['user_id']},
							`GoodId` = {$data['pay_car_good']}, 
							`ContentId` = {$data['field_id']},
							`ContentId2` = {$work->Id},
							`Text` = '{$fieldMsg->FieldName}',
							`Text2` = '{$work->Name}'";
            $result = db_query($sql_str);
            if ($result === FALSE) return db_error();
            $pay_car_id = db_insert_id(); // 插入的购物车id

            // 添加作品
            $result = $myUser->user_field_workadd($data['field_id'], $work->Id, 0, $pay_car_id);
            if ($result !== 1) return $result;

            $count++;
        }
        return $count;
    }

    /** 用户支付完成后 将购物车中的所有商品（本领编辑）发布 成功返回1 失败返回错误信息 */
    public function pay_car_release(&$order_id)
    {
        $myUser = new user_m();
        // db_begin(); 20171119 此处事务由上层调用者管理
        // 查询当前用户下的所有的购物车
        $sql_str = "SELECT * FROM `user_pay_car` 
					WHERE `UserId` = {$_SESSION['user_id']}";
        $pay_car_list = db_query($sql_str);
        if ($pay_car_list === FALSE) return db_error();
        $rows = array();
        $price = 0;
        while ($row = $pay_car_list->fetch_object()) {
            // 更新内容 使前台可见
            if ($row->GoodId == CPay::GoodsType_FieldAdd) {
                $result = $myUser->user_field_set_show($row->ContentId, 1);
            } elseif ($row->GoodId == CPay::GoodsType_FieldIntrod) {
                $result = $myUser->user_field_update_introd($row->ContentId);
            } elseif ($row->GoodId == CPay::GoodsType_FieldName) {
                $result = $myUser->user_field_update_name($row->ContentId);
            } elseif ($row->GoodId == CPay::GoodsType_FieldWorkAdd) {
                $result = $myUser->user_field_work_set_show($row->ContentId, $row->ContentId2, 1);
            }
            if ($result !== 1) {
                return $result;
            }
            // 计算总价
            $row->Price = $this->get_good_price($row->GoodId);
            $price += $row->Price;
            $rows[] = $row;
        }
        // 插入消费记录
        $result = $this->consume_insert(CPay::ConsumeType_FieldEdit, $price, $order_id);
        if ($result != 1) {
            return $result;
        }
        // 插入消费记录的内容
        foreach ($rows as $good) {
            $result = $this->consume_content_insert($good, $order_id);
            if (!is_numeric($result)) {
                return $result;
            }
        }

        // 消费数据统计更新
        $result = $this->consume_count_record($price);
        if ($result !== 1) return db_error();

        // 更新购物车数量为0
        $sql_str = "UPDATE `users` SET `PayCarCount` = 0 
					WHERE `Id` = {$_SESSION['user_id']}";
        $result = db_query($sql_str);
        if ($result === FALSE) return db_error();

        // 将购物车内容清空
        $sql_str = "DELETE FROM `user_pay_car` 
					WHERE `UserId` = {$_SESSION['user_id']}";
        $result = db_query($sql_str);
        if ($result === FALSE) return db_error();
        // db_commit(); 20171119 此处事务由上层调用者管理
        return 1;
    }

    /**
     * 插入消费单 成功返回1 失败返回错误信息
     * $type 消费单类型 参考常量
     * $price 消费单总价
     * $order_id 订单号
     */
    public function consume_insert($type, $price, $order_id)
    {
        // 插入消费单
        $sql_str = "INSERT INTO user_consume 
					SET `Id` = '{$order_id}',
						`UserId` = {$_SESSION['user_id']}, 
						`Type` = {$type},
						`Price` = {$price}";
        $result = db_query($sql_str);
        if ($result === FALSE) return db_error();
        return 1;
    }

    /**
     * 插入消费单的内容 成功返回插入的id
     */
    public function consume_content_insert(&$good, $consume_id)
    {
        //if (!is_numeric($consume_id)) return '插入消费单内容时，消费单信息错误';
        $sql_str = "INSERT INTO user_consume_content 
					SET ConsumeId = '{$consume_id}',
					    GoodId = {$good->GoodId},
						Price = {$good->Price},
						SubId = {$good->ContentId},
						SubId2 = {$good->ContentId2},
						`Text` = '{$good->Text}',
						`Text2` = '{$good->Text2}'";
        $result = db_query($sql_str);
        if ($result === FALSE) return db_error();
        $content_id = db_insert_id();
        if ($content_id <= 0) return '插入消费单内容时错误';
        return $content_id;
    }

    /**
     * 消费数据统计 成功返回1 失败返回错误信息
     * $price 消费的金额
     * $type  1作品发布 2鞋主秀发布
     */
    public function consume_count_record($price, $type = 0)
    {
        // 统计当前日期的记录
        // 获取当前日期
        $d = date('Y-m-d');
        $sql_str = "INSERT INTO user_consume_count 
					SET ConsumeDate = '{$d}',
					    TotalPrice = {$price}";
        if ($type == 1)
            $sql_str .= ' , WorksCount = 1';
        elseif ($type == 2)
            $sql_str .= ' , ShowCount = 1';
        // 如果当前日期已有数据 则累加
        $sql_str .= " ON DUPLICATE KEY 
					 UPDATE TotalPrice = TotalPrice + {$price}";
        if ($type == 1)
            $sql_str .= ' , WorksCount = WorksCount + 1';
        elseif ($type == 2)
            $sql_str .= ' , ShowCount = ShowCount + 1';

        $result = db_query($sql_str);
        if ($result === FALSE) return db_error();

        // 统计总记录
        $sql_str = "UPDATE user_consume_total 
					SET TotalPrice = TotalPrice + {$price},
					    TotalCount = TotalCount + 1";
        if ($type == 1)
            $sql_str .= ' , WorksCount = WorksCount + 1';
        elseif ($type == 2)
            $sql_str .= ' , ShowCount = ShowCount + 1';
        $sql_str .= ' WHERE `Id` = 1';
        $result = db_query($sql_str);
        if ($result === FALSE) return db_error();

        return 1;
    }

    /**
     * 购物车结算
     * $pay_tool 支付工具
     */
    public function pay_car_accounts($pay_tool)
    {
        if (!is_numeric($pay_tool)) return '购物车结算时，提交的支付工具错误';
        $myUser = new user_m();
        db_begin();

        // 查询当前用户下的所有的购物车
        $sql_str = "SELECT * FROM `user_pay_car` 
					WHERE `UserId` = {$_SESSION['user_id']}";
        $pay_car_list = db_query($sql_str);
        if ($pay_car_list === FALSE) return db_rollback();
        $price = 0;
        $ids = '';
        $rows = array();
        while ($row = $pay_car_list->fetch_object()) {
            // 更新内容 使前台可见
            if ($row->GoodId == CPay::GoodsType_FieldAdd) {
                $result = $myUser->user_field_set_show($row->ContentId, 1);

            } elseif ($row->GoodId == CPay::GoodsType_FieldIntrod) {
                $result = $myUser->user_field_update_introd($row->ContentId);
            } elseif ($row->GoodId == CPay::GoodsType_FieldName) {
                $result = $myUser->user_field_update_name($row->ContentId);
            } elseif ($row->GoodId == CPay::GoodsType_FieldWorkAdd) {
                $result = $myUser->user_field_work_set_show($row->ContentId, $row->ContentId2, 1);
            }
            if ($result !== 1) {
                db_rollback();
                return $result;
            }

            // 计算总价
            $row->Price = $this->get_good_price($row->GoodId);
            $price += $row->Price;
            $rows[] = $row;
        }

        // 支付
        $result = $this->pay_submit($pay_tool, $price, 1, '购物车结算');
        if ($result === 0) {
            db_rollback();
            return '您的余额不足';
        }
        if ($result !== 1) {
            db_rollback();
            return $result;
        }

        // 插入消费记录
        $consume_id = $this->consume_insert(3, $price);
        if (!is_numeric($consume_id)) {
            db_rollback();
            return $consume_id;
        }
        // 插入消费记录的内容
        foreach ($rows as $good) {
            $result = $this->consume_content_insert($good, $consume_id);
            if (!is_numeric($result)) {
                db_rollback();
                return $result;
            }
        }

        // 消费数据统计更新
        $result = $this->consume_count_record($price);
        if ($result !== 1) return db_rollback();

        // 更新购物车数量为0
        $sql_str = "UPDATE `users` SET `PayCarCount` = 0 
					WHERE `Id` = {$_SESSION['user_id']}";
        $result = db_query($sql_str);
        if ($result === FALSE) return db_rollback();

        // 将购物车内容清空
        $sql_str = "DELETE FROM `user_pay_car` 
					WHERE `UserId` = {$_SESSION['user_id']}";
        $result = db_query($sql_str);
        if ($result === FALSE) return db_rollback();

        db_commit();
        return 1;
    }

    /**
     * 用户支付提交处理 成功将返回1和需要重定向的url 失败返回错误信息
     * @param int $tool 支付工具
     * @param double $total_fee 支付单价
     * @param string $order_id 订单ID
     * @param string $redirect_url 返回重定向的url
     */
    public function pay_submit($tool, $total_fee, &$order_id, &$redirect_url)
    {
        if (!is_numeric($tool) || !is_numeric($total_fee)) {
            $this->error = '支付时，提交的信息错误';
            return FALSE;
        }
        if ($tool == CPay::PayToolZhiFuBao) {
            return '尚不支持支付宝支付接口';
            if ($this->alipay_config == null) {
                return '支付宝配置为空';
            }
            //return $this->pay_submit_zhifubao($count, $row->Price, $row->Text, )
        } elseif ($tool == CPay::PayToolWeiXin) {
            return $this->pay_submit_weixin($total_fee, $order_id, $redirect_url);
        } elseif ($tool == CPay::PayToolBalance) {
            return $this->pay_submit_balance($total_fee, $order_id, $redirect_url);
        }
    }

    /**
     * 支付提交 微信
     * @param int $total_fee 总金额
     * @param string $order_id 订单号
     */
    private function pay_submit_weixin($total_fee, &$order_id, &$redirect_url)
    {
        global $CfgPara; // 全局参数
        $data = $this->weixin_get_req_para($total_fee, $order_id);
        $postdata = http_build_query($data);
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-type:application/x-www-form-urlencoded',
                'content' => $postdata,
                'timeout' => 10 * 60 // 超时时间 单位:s
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($this->WeiXinPay_Url, false, $context);
        if ($result) {
            $xml = simplexml_load_string($result);
            if ($xml == false) {
                return "提交微信支付订单时 返回信息无法解析为XML";
            }
            try {
                if ((string)$xml->return_code != "SUCCESS") {
                    return "提交微信支付订单时 与微信服务器通信失败";
                }
                if ((string)$xml->result_code != "SUCCESS") {
                    return (string)$xml->err_code_des; // 返回错误描述
                }
                $prepay_id = (string)$xml->prepay_id;
                // 跳转到指定微信支付页面 并添加参数redirect_url 要求微信后台支付操作后，跳转到指定页面
                $mweb_url = (string)$xml->mweb_url; // 返回的微信后台要求跳转的页面
                $redirect_url = urlencode("{$CfgPara->$httproot}/{$this->WeiXinPay_Redirect_Url}/{$order_id}.html");
                $mweb_url .= "&redirect_url={$redirect_url}";
                $redirect_url = $mweb_url;
            } catch (Exception $e) {
                return "提交微信支付订单时 解析返回的结果错误";
            }
        } else {
            return "提交微信支付订单时 未知错误";
        }
        return 1;
    }

    /**
     * 微信支付 获取统一下单申请参数 返回参数数组
     * @param string $text 商品描述
     * @param string $total_fee 交易金额
     */
    public function weixin_get_req_para($total_fee, $order_id)
    {
        global $CfgPara;
        // 生成随机字符串
        $nonce_str = $this->get_random(32);
        // 商户订单号
        $out_trade_no = $order_id;
        // 生成订单过期时间
        $time_expire = date("YmdHis", strtotime("+12 hours"));
        // 获取用户端IP
        $spbill_create_ip = $this->get_ip();
        // 支付成功后 微信后台调用的页面
        $notify_url = urlencode($CfgPara->httproot . '/' . $this->WeiXinPay_Notify_Url . '/' . $order_id . '.html');
        // 生成签名需要的字符串 参数按ASCII字典顺序排列 最后拼接上密钥
        $sign_s = "appid={$this->WeiXinPay_AppID}&body=SneakerCustom-支付&mch_id={$this->WeiXinPay_MchID}&nonce_str={$nonce_str}&notify_url={notify_url}&out_trade_no={$out_trade_no}&spbill_create_ip={$spbill_create_ip}&time_expire={$time_expire}&total_fee={$total_fee}&trade_type=MWEB&key={$this->WeiXinPay_APIKey}";
        // 生成MD5签名
        $sign = strtoupper(md5($sign_s));
        // 生成最终发送的参数值
        $send = array(
            "appid" => $this->WeiXinPay_AppID,
            "body" => "SneakerCustom-支付",
            "mch_id" => $this->WeiXinPay_MchID,
            "nonce_str" => $nonce_str,
            "notify_url" => $notify_url,
            "out_trade_no" => $out_trade_no,
            "spbill_create_ip" => $spbill_create_ip,
            "time_expire" => $time_expire,
            "total_fee" => $total_fee,
            "sign" => $sign
        );
        return $send;
    }

    /**
     * 获取随机字符串
     * @param int $lenght 字符串长度
     */
    public function get_random($lenght)
    {
        $str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $len = strlen($str) - 1;
        $randstr = '';
        for ($i = 0; $i < $lenght; $i++) {
            $num = mt_rand(0, $len);
            $randstr .= $str[$num];
        }
        return $randstr;
    }

    /** 获取用户端IP地址 */
    public function get_ip()
    {
        $cip = "unknown";
        if ($_SERVER["REMOTE_ADDR"]) {
            $cip = $_SERVER["REMOTE_ADDR"];
        } elseif (getenv("REMOTE_ADDR")) {
            $cip = getenv("REMOTE_ADDR");
        }
        return $cip;
    }

    /** 支付提交 使用余额支付 此处仅检查余额 */
    private function pay_submit_balance($total_fee, &$order_id, &$redirect_url)
    {
        global $CfgPara;
        // 数据库中获取当前用户余额
        $sql_str = "SELECT `Balance` FROM `users` WHERE `Id` = {$_SESSION['user_id']}";
        $result = db_query($sql_str);
        if ($result !== FALSE) {
            if ($row = $result->fetch_object()) {
                $balance = $row->Balance;
            }
        } else {
            return db_error();
        }
        if (!isset ($balance) || $balance < $total_fee) {
            return "账户余额不足";
        }
        // 跳转到支付成功页面 由此页面在确认后将余额扣除
        $redirect_url = "{$CfgPara->httproot}/{$this->BalancePay_Notify_Url}/{$order_id}.html";
        return 1;
    }

    /** 根据商品Id 获取消费类型Id */
    public function get_consume_type($good_id)
    {
        $good_id = (int)$good_id;
        switch ($good_id) {
            case CPay::GoodsType_Balance:
                return CPay::ConsumeType_Balance;
            case CPay::GoodsType_ShowRelease:
                return CPay::ConsumeType_ShowRelease;
            case CPay::GoodsType_WorkRelease:
                return CPay::ConsumeType_WorkRelease;
            case CPay::GoodsType_FieldAdd:
                return CPay::ConsumeType_FieldEdit;
            case CPay::GoodsType_FieldIntrod:
                return CPay::ConsumeType_FieldEdit;
            case CPay::GoodsType_FieldName:
                return CPay::ConsumeType_FieldEdit;
            case CPay::GoodsType_FieldWorkAdd:
                return CPay::ConsumeType_FieldEdit;
            case CPay::GoodsType_FieldWorkDele:
                return CPay::ConsumeType_FieldEdit;
            default:
                return -1;
        }
    }

    /**
     * 插入消费单的内容 成功返回插入的id
     */
    public function consume_content_insert2($consume_id, $price, $id, $id2 = 0)
    {
        $sql_str = "INSERT INTO user_consume_content 
					SET ConsumeId = {$consume_id},
					    GoodId = {$good->GoodId},
						Price = {$price},
						SubId = {$id},
						SubId2 = {$id2}";
        $result = db_query($sql_str);
        if ($result === FALSE) return db_error();
        $content_id = db_insert_id();
        if ($content_id <= 0) return '插入消费单内容时错误';
        return $content_id;
    }

    /**
     * 获取消费上月统计信息
     */
    public function consume_lastmonth_count()
    {
        //获取当前日期的上个月的最后一天
        //$curtime = data('Y-m-d');
        //$time=strtotime($curtime);
        //date('Y-m-t',strtotime('last month',$time));
        $d2 = date('Y-m-t', strtotime('last month'));
        $d1 = date('Y-m-1', strtotime('last month'));
        $sql_str = "SELECT SUM(TotalPrice) as TotalPrice, 
		                   SUM(WorksCount) as WorksCount, 
						   SUM(ShowCount) as ShowCount
					FROM user_consume_count 
					WHERE ConsumeDate >= '{$d1}' AND ConsumeDate <= '{$d2}'";
        $result = db_query($sql_str);
        if ($result === FALSE) return db_error();
        if ($row = $result->fetch_object()) {
            if (isset($row->TotalPrice))
                return $row;
            else
                return $this->consume_count_return_0();
        } else {
            return $this->consume_count_return_0();
        }
    }

    /**
     * 用户消费统计返回0
     */
    public function consume_count_return_0()
    {
        $row = new stdClass();
        $row->TotalPrice = 0;
        $row->WorksCount = 0;
        $row->ShowCount = 0;
        $row->TotalCount = 0;
        return $row;
    }

    /**
     * 获取消费今日统计信息
     */
    public function consume_today_count()
    {
        $d = date('Y-m-d'); // 当前日期
        $sql_str = "SELECT TotalPrice, WorksCount, ShowCount 
					FROM user_consume_count 
					WHERE ConsumeDate = '{$d}'";
        $result = db_query($sql_str);
        if ($result === FALSE) return db_error();
        if ($row = $result->fetch_object()) {
            return $row;
        } else {
            return $this->consume_count_return_0();
        }
        return $row;
    }

    /**
     * 获取消费总的统计信息
     */
    public function consume_total_count()
    {
        $sql_str = "SELECT TotalPrice, WorksCount, ShowCount, TotalCount 
					FROM user_consume_total 
					WHERE Id = 1";
        $result = db_query($sql_str);
        if ($result === FALSE) return db_error();
        if ($row = $result->fetch_object()) {
            return $row;
        } else {
            return $this->consume_count_return_0();
        }
        return $row;
    }

    /**
     * 获取消费单列表 成功返回消费单的对象数组 失败返回错误信息
     * @param int $page 第几页
     * @param int $page_size 每页的数量
     */
    public function consume_list($page, $page_size)
    {
        $limit_count = $page_size; // 每页的数量
        $limit_offset = ($page - 1) * $page_size; // 计算偏移量
        $sql_str = "SELECT `user_consume`.`Id`,
						   `users`.`Name` as UserName,`user_consume`.`Type`, 
						   `user_consume`.`Type`,`user_consume`.`Price`,
						   DATE_FORMAT(`user_consume`.`ConsumeDt`, '%Y.%m.%d %H:%i') as ConsumeDt
					FROM `user_consume`,`users` 
					WHERE `user_consume`.`UserId` = `users`.`Id`
					ORDER BY `user_consume`.`ConsumeDt` DESC
					LIMIT {$limit_offset},{$limit_count}";
        $result = db_query($sql_str);
        if ($result === FALSE) return db_error();
        $rows = array();
        while (db_fetch_object($result, $row)) {
            $desc_resutl = $this->get_consume_type_desc($row);
            if ($desc_resutl !== 1) return $desc_resutl;
            $rows[] = $row;
        }
        return $rows;
    }

    /**
     * 获取消费类型的标题与描述 传入的对象实例将增加Tittle与Desc属性
     * 成功返回1 失败返回错误信息
     * @param object $consume 消费单的对象实例
     */
    public function get_consume_type_desc(&$consume)
    {
        $type = (int)$consume->Type;
        switch ($type) {
            case CPay::ConsumeType_Balance:
                $consume->Tittle = '余额充值';
                $consume->Desc = '';
                break;
            case CPay::ConsumeType_ShowRelease:
                $consume->Tittle = '鞋主秀发布';
                // 获取鞋主秀所属的作品的名称
                $sql_str = "SELECT `works`.`Name` 
							FROM `user_consume_content`,`works`,`shoe_show` 
							WHERE `user_consume_content`.`ConsumeId` = {$consume->Id} AND 
							      `user_consume_content`.`SubId` = `shoe_show`.`Id` AND 
								  `shoe_show`.`WorkId` = `works`.`Id`";
                $result = db_query($sql_str);
                if ($result === FALSE) return db_error();
                $result = db_fetch_object($result, $workMsg);
                if ($result === 1) $consume->Desc = $workMsg->Name;
                else $consume->Desc = '无法获取作品名';
                break;
            case CPay::ConsumeType_WorkRelease:
                $consume->Tittle = '作品发布';
                // 获取作品的名称
                $sql_str = "SELECT `works`.`Name` 
							FROM `user_consume_content`,`works` 
							WHERE `user_consume_content`.`ConsumeId` = {$consume->Id} AND 
							      `user_consume_content`.`SubId` = `works`.`Id`";
                $result = db_query($sql_str);
                if ($result === FALSE) return db_error();
                $result = db_fetch_object($result, $workMsg);
                if ($result === 1) $consume->Desc = $workMsg->Name;
                else $consume->Desc = '无法获取作品名';
                break;
            case CPay::ConsumeType_FieldEdit:
                $consume->Tittle = '本领编辑';
                $consume->Desc = '';
                break;
        }
        return 1;
    }

    /**
     * 获取消费单列表 成功返回消费单的具体内容的对象数组 失败返回错误信息
     * @param int $id 消费单id
     * @param $page_size 每页的数量
     */
    public function consume_content_list($id)
    {
        if (!is_numeric($id)) return '获取消费具体内容时，提交的信息错误';
        $sql_str = "SELECT GoodId,Price,SubId,SubId2,`Text`,`Text2` 
					FROM user_consume_content 
					WHERE ConsumeId = {$id}";
        $result = db_query($sql_str);
        if ($result === FALSE) return db_error();
        $rows = array();
        while (db_fetch_object($result, $row) === 1) {
            $desc_resutl = $this->get_good_desc($row->GoodId, $row);
            if ($desc_resutl !== 1) return '获取消费单内容的标题/文本时错误';
            $rows[] = $row;
        }
        return $rows;
    }

    /**
     * 提交订单 写入订单数据表 成功返回1和订单ID和订单总价 失败返回错误信息
     * @param object $data 提交的订单数据
     * @param string $order_id 返回订单Id
     * @param double $total_fee 返回订单总价
     */
    public function pay_neworder(&$data, &$order_id, &$total_fee)
    {
        if (!isset($_SESSION['user_id']) || !is_numeric($_SESSION['user_id'])) {
            return "提交订单时 请先登陆";
        }
        if (!isset($data['PayTool']) || !isset($data['PayType']) || !isset($data['PayTotalFee']) ||
            !is_numeric($data['PayTool']) || !is_numeric($data['PayType']) || !is_numeric($data['PayTotalFee'])
        ) {
            return "提交订单时 订单参数错误";
        }
        $total_fee = 0;
        // 订单标题与描述 以及确认支付金额
        if ($data['PayType'] == CPay::ConsumeType_Balance) {
            $tittle = "充值余额";
            $text = "";
            $subid = 0;
            $total_fee = $data['PayTotalFee'];
        } elseif ($data['PayType'] == CPay::ConsumeType_WorkRelease) {
            $total_fee = CPay::GoodsPrice_WorkRelease;
            if (!isset($data['work_name']) || !isset($data['introd']) || !isset($data['work_id'])) {
                return "提交订单时 没找到作品数据";
            }
            $tittle = "发布作品：";
            $tittle .= urldecode($data['work_name']);
            $text = urldecode($data['introd']);
            $subid = $data['work_id'];
        } elseif ($data['PayType'] == CPay::ConsumeType_ShowRelease) {
            $total_fee = CPay::GoodsPrice_ShowRelease;
            if (!isset($data['introd']) || !isset($data['shoe_show_id'])) {
                return "提交订单时 没找到鞋主秀数据";
            }
            $tittle = "发布鞋主秀";
            $text = urldecode($data['introd']);
            $subid = $data['shoe_show_id'];
        } elseif ($data['PayType'] == CPay::ConsumeType_FieldEdit) {
            $total_fee = $this->pay_car_totalfee();
            if (!isset($_SESSION['user_name'])) {
                return "提交订单时 没找到用户数据";
            }
            $tittle = "本领编辑：{$_SESSION['user_name']}";
            $text = "";
            $subid = $_SESSION['user_id'];
        } else {
            return "提交订单时 消费类型错误";
        }
        // 生成订单号
        $order_id = $this->get_order_id();
        $sql_str = "INSERT INTO user_pay_order 
					SET `Id` = '{$order_id}',
						`PayTool` = {$data['PayTool']},
						`Type` = {$data['PayType']},
						`SubId` = {$subid},
						`TotalFee` = {$total_fee},
						`Tittle` = '{$tittle}',
						`Text` = '{$text}',
						`State` = 0;";
        $result = db_query($sql_str);
        if ($result === FALSE) {
            return db_error();
        }
        return 1;
    }

    /** 获取购物车所有商品价格 成功返回总价 失败返回错误信息 */
    public function pay_car_totalfee()
    {
        // 查询当前用户下的所有的购物车
        $sql_str = "SELECT * FROM `user_pay_car` 
					WHERE `UserId` = {$_SESSION['user_id']}";
        $pay_car_list = db_query($sql_str);
        if ($pay_car_list === FALSE) return db_error();
        $price = 0;
        $good_price = 0;
        while ($row = $pay_car_list->fetch_object()) {
            // 计算总价
            $good_price = $this->get_good_price($row->GoodId);
            if (!is_numeric($good_price)) return "购物车计算总价时 商品ID错误";
            $price += $row->Price;
        }
        return $price;
    }

    /** 获取支付订单号 */
    public function get_order_id()
    {
        // 订单号格式时间+用户ID+随机数
        $d = date("YmdHis");
        $r = $this->get_random(5);
        $id = $_SESSION["user_id"];
        $s = "$d-$id-$r";
        if (strlen($s) > 32) {
            $s = substr($s, 0, 32);
        }
        return $s;
    }

    /** 查询订单数据 如果成功返回订单数据对象 如果失败返回错误信息 */
    public function get_order_data(&$order_id)
    {
        if (!isset($order_id)) {
            return "查询订单数据时 订单id错误";
        }
        $sql = "SELECT * FROM `user_pay_order` WHERE `Id` = '{$order_id}';";
        $result = db_query($sql);
        if ($result !== FALSE) {
            if ($row = $result->fetch_object()) {
                return $row;
            } else {
                return "查询订单数据时 生成数据对象错误";
            }
        } else {
            return db_error();
        }
        return 1;
    }

    /** 设置支付订单状态 设置成功返回1 失败返回错误信息 */
    public function set_order_pay_s(&$order_id, $state)
    {
        if (!isset($order_id)) {
            return "设置订单支付状态时 订单id错误";
        }
        if (!is_numeric($state)) {
            return "设置订单支付状态时 提交的状态错误";
        }
        $sql = "UPDATE `user_pay_order` 
				SET `State` = {$state} 
				WHERE `Id` = '{$order_id}'";
        $result = db_query($sql);
        if ($result === FALSE) {
            return db_error();
        }
        if (db_affected_rows() <= 0) {
            return "设置订单支付状态时 未找到相关订单";
        }
        return 1;
    }

    /**
     * 加减用户余额 成功返回操作后的余额 失败返回错误信息
     * @param int $n 需要加减的数值
     * @param bool $add 1为加 0为减
     */
    public function set_balance($n, $add)
    {
        if (!is_numeric($n)) {
            return "后台操作余额时，提交的操作数值错误";
        }
        $balance = -1;
        // 数据库中获取当前用户余额
        $sql = "SELECT `Balance` FROM `users` WHERE `Id` = {$_SESSION['user_id']} FOR UPDATE";
        $result = db_query($sql);
        if ($result !== FALSE) {
            if ($row = $result->fetch_object()) {
                $balance = $row->Balance;
            }
        } else {
            return db_error();
        }
        if ($balance < 0) {
            return "后台操作余额时，获取的余额数值错误";
        }
        if ($n == 0) // 如果操作值为0 直接返回余额
        {
            return $balance;
        }
        if ($add != 1) // 如果是减的话 需要先判断余额是否足够
        {
            if ($balance < $n) {
                return "账户余额不足";
            }
            $balance -= $n;
        } else {
            $balance += $n;
        }
        // 设置账户余额
        $sql_str = "UPDATE `users` 
					SET `Balance` = '{$balance}' 
					WHERE `Id` = {$_SESSION['user_id']}";
        $result = db_query($sql_str);
        if ($result === FALSE) {
            return db_error();
        }
        return $balance;
    }

    /** 到微信服务器查询订单状态 订单支付成功返回1 失败返回相关信息*/
    public function weixin_orderquery(&$order_id)
    {
        // 生成随机字符串
        $nonce_str = $this->get_random(32);
        $out_trade_no = $order_id;
        // 生成签名需要的字符串 参数按ASCII字典顺序排列 最后拼接上密钥
        $sign_s = "appid={$this->WeiXinPay_AppID}&mch_id={$this->WeiXinPay_MchID}&nonce_str={$nonce_str}&out_trade_no={$out_trade_no}&key={$this->WeiXinPay_APIKey}";
        // 生成MD5签名
        $sign = strtoupper(md5($sign_s));
        // 生成查询参数
        $data = array(
            'appid' => $this->WeiXinPay_AppID,
            'mch_id' => $this->WeiXinPay_MchID,
            'nonce_str' => $nonce_str,
            'out_trade_no' => $out_trade_no,
            'sign' => $sign
        );
        $postdata = http_build_query($data);
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-type:application/x-www-form-urlencoded',
                'content' => $postdata,
                'timeout' => 10 * 60 // 超时时间 单位:s
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($this->WeiXinPay_Url, false, $context);
        if ($result) {
            $xml = simplexml_load_string($result);
            if ($xml == false) {
                return "查询微信支付订单时 返回信息无法解析为XML";
            }
            try {
                if ((string)$xml->return_code != "SUCCESS") {
                    return "查询微信支付订单时 与微信服务器通信失败";
                }
                if ((string)$xml->result_code != "SUCCESS") {
                    return (string)$xml->err_code_des; // 返回错误描述
                }
                $state = (string)$xml->trade_state;
                if ($state == "SUCCESS") {
                    return 1;
                } else {
                    return $this->get_trade_state_text($state);
                }
            } catch (Exception $e) {
                return "提交微信支付订单时 解析返回的结果错误";
            }
        } else {
            return "提交微信支付订单时 未知错误";
        }
    }

    /** 获取支付订单的状态描述 */
    public function get_trade_state_text($state)
    {
        if ($state == 'SUCCESS') {
            return '支付成功';
        } elseif ($state == 'REFUND') {
            return '转入退款';
        } elseif ($state == 'NOTPAY') {
            return '未支付';
        } elseif ($state == 'CLOSED') {
            return '已关闭';
        } elseif ($state == 'REVOKED') {
            return '已撤销（刷卡支付）';
        } elseif ($state == 'USERPAYING') {
            return '用户支付中';
        } elseif ($state == 'PAYERROR') {
            return '支付失败(其他原因，如银行返回失败)';
        } else {
            return '未知状态';
        }
    }

    private function pay_submit_zhifubao($count, $price, $text, $alipay_config)
    {
        //引入支付宝接口配置与API的工作已在调用此类前完成（在controller中判断）
        /**************************请求参数**************************/

        //商户订单号，商户网站订单系统中唯一订单号，必填
        $out_trade_no = $_POST['WIDout_trade_no'];

        //订单名称，必填 此处使用商品名称
        $subject = $text;

        //付款金额，必填
        $total_fee = $_POST['WIDtotal_fee'];

        //收银台页面上，商品展示的超链接，必填
        $show_url = $_POST['WIDshow_url'];

        //商品描述，可空
        $body = $_POST['WIDbody'];
        /************************************************************/
        //构造要请求的参数数组，无需改动
        $parameter = array(
            "service" => $alipay_config['service'],
            "partner" => $alipay_config['partner'],
            "seller_id" => $alipay_config['seller_id'],
            "payment_type" => $alipay_config['payment_type'],
            "notify_url" => $alipay_config['notify_url'],
            "return_url" => $alipay_config['return_url'],
            "_input_charset" => trim(strtolower($alipay_config['input_charset'])),
            "out_trade_no" => $out_trade_no,
            "subject" => $subject,
            "total_fee" => $total_fee,
            "show_url" => $show_url,
            "body" => $body,
            //其他业务参数根据在线开发文档，添加参数.文档地址:https://doc.open.alipay.com/doc2/detail.htm?spm=a219a.7629140.0.0.2Z6TSk&treeId=60&articleId=103693&docType=1
            //如"参数名"	=> "参数值"   注：上一个参数末尾需要“,”逗号。
        );

        //建立请求
        $alipaySubmit = new AlipaySubmit($alipay_config);
        $this->$submit_html_text = $alipaySubmit->buildRequestForm($parameter, "get", "确认");
        return 1;
    }
}